package com.example.demo.controller;

import com.example.demo.domain.LoginDto;
import com.example.demo.domain.Result;
import com.example.demo.service.UserService;
import com.example.demo.utils.JwtUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

/**
 * @author wsj
 */
@RestController
@RequiredArgsConstructor
public class UserController {

    private final UserService userService;

    private final JwtUtil jwtUtil;

    private final RedisTemplate<String, String> redisTemplate;
    @GetMapping("/test")
    public String test() {
        return "Hello World!";
    }

    @PostMapping("/login")
    public Result login(@RequestBody LoginDto loginDto) {
        String token = userService.login(loginDto);
        return Result.success(token);
    }

    @PostMapping ("/logout")
    public Result logout(@RequestHeader("token") String token) {
        Integer userId = jwtUtil.getUsernameFromToken(token);
        SecurityContextHolder.clearContext();
        redisTemplate.delete(String.valueOf(userId));
        return Result.success();
    }
}
